package com.combetter.changxing.ui.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.combetter.changxing.db.entity.User;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.util.AppManager;
import com.combetter.changxing.util.LogUtil;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.R;
import com.combetter.changxing.bluetooth.FacilityClient2;
import com.combetter.changxing.databinding.ActivityMainBinding;
import com.combetter.changxing.model.EventMessage;
import com.combetter.changxing.ui.base.BaseActivity;
import com.combetter.changxing.ui.dialog.LoadingDialog;
import com.combetter.changxing.ui.fragment.FacilityFragmentReWrite;
import com.combetter.changxing.ui.fragment.HistoryFragment;
import com.combetter.changxing.ui.fragment.HomeFragment;
import com.combetter.changxing.ui.fragment.MineFragment;
import com.combetter.changxing.util.SharePreferencesUtils;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.MainViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {
    private boolean mIsExit;
    /**
     * 封装了tab信息的集合
     */
    private ArrayList<CustomTabEntity> mCustomTabEntities;
    private String[] mTitles = {"首页", "设备", "记录", "我的"};
    private int[] selectIcon = {R.mipmap.sy_shouye_sel, R.mipmap.sy_shebei_sel, R.mipmap.sy_jilu_sel, R.mipmap.sy_wode_sel};
    private int[] unSelectedIcon = {R.mipmap.sy_shouye_nor, R.mipmap.sy_shebei_nor, R.mipmap.sy_jilu_nor, R.mipmap.sy_wode_nor};
    private ArrayList<Fragment> mFragments;
    private LoadingDialog loadingDialog;


    @Override
    public int setLayout() {
        EventBus.getDefault().register(this);
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        mFragments = new ArrayList<>();
        mFragments.add(new HomeFragment());
        mFragments.add(new FacilityFragmentReWrite());
        mFragments.add(new HistoryFragment());
        mFragments.add(new MineFragment());
        setViewpager();
        loadingDialog = new LoadingDialog(this);

    }

    /**
     * 注意别填错了
     *
     * @return
     */
    @Override
    public Class<MainViewModel> createViewModel() {
        return MainViewModel.class;
    }

    @Override
    public void loadData() {
        SharePreferencesUtils utils = new SharePreferencesUtils(MyApp.getInstance());
        String deviceMac = utils.getConnectDevice();
        if (!TextUtils.isEmpty(deviceMac) && MyApp.getInstance().getDatabase().facilityDao().findByMac(deviceMac) != null) {
            if (loadingDialog != null) {
                loadingDialog.setMsg("鉴权中...");
                loadingDialog.show();
            }
            FacilityClient2.getClient().connect(deviceMac);
        }
    }


    /**
     * 设置viewpager数据
     */
    private void setViewpager() {
        mCustomTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            final int finalI = i;
            mCustomTabEntities.add(new CustomTabEntity() {
                @Override
                public String getTabTitle() {
                    return mTitles[finalI];
                }

                @Override
                public int getTabSelectedIcon() {
                    return selectIcon[finalI];
                }

                @Override
                public int getTabUnselectedIcon() {
                    return unSelectedIcon[finalI];
                }
            });
        }
        mBinding.tabLayout.setTabData(mCustomTabEntities, this, R.id.content_frame, mFragments);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventData(EventMessage message) {
        switch (message.getType()) {
            // 蓝牙连接成功
            case "BleAuthSuccess":
                break;
            //已配对的设备列表回调
            case "connectFail":
                break;
            case "onDisConnected":
                break;
            case "AuthFail":
                break;
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }


    /**
     * 双击返回键退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsExit) {
                this.finish();
            } else {
                ToastUtils.showToast("再按一次退出");
                mIsExit = true;
                Observable.timer(2000, TimeUnit.MILLISECONDS)
                        .doOnComplete(() -> mIsExit = false)
                        .subscribe();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (!JPushInterface.isPushStopped(this)) {
            JPushInterface.stopPush(this);
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        JPushInterface.onPause(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.resumePush(this);
    }
}
